//
//  DDNetTools.swift
//  SinaMicroBlog
//
//  Created by dqw on 15/7/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

private let DDErrorDomainName = "DDErrorDomainName"

class DDNetTools: AFHTTPSessionManager {

    typealias DDNetFinishedCT = (result:[String:AnyObject]?, error:NSError?) ->()
    
    static let sharedNetTools:DDNetTools = {
        let instance = DDNetTools(baseURL: NSURL(string: "https://api.weibo.com")!)
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return instance
    }()
    
    private var clientId = "167165570"
    private var clientSecret = "efe9033ed60e584f9bd158a1aee4e4b7"
    var redirectUri = "http://www.baidu.com"

    var oauthUrl: NSURL{
       return NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)")!
    }
    
    func getAccessTokenAndSomeUserInfo(code:String, finished : DDNetFinishedCT){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let paras = ["client_id": clientId,
            "client_secret": clientSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        DDPostRequest(urlString, paras: paras, finished: finished)
        
//        POST(urlString, parameters: paras, success: { (_, JSON) -> Void in
//            finished(result: JSON as? [String:AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                finished(result: nil, error: error)
//        }
    }
    
    func getAnotherUserInfo(finished:DDNetFinishedCT) {
        
        let urlStr = "2/users/show.json"
        let aUserAccount: DDUserAccount? = DDUserAccount.loadUserAccount()
        if aUserAccount?.access_token == nil || aUserAccount?.uid == nil {
            return
        }
        
        let paras:[String: AnyObject] = ["access_token": aUserAccount!.access_token!, "uid": aUserAccount!.uid!]
        DDGetRequest(urlStr, paras: paras, finished: finished)
        
    }
    
    private let DDError = NSError(domain: DDErrorDomainName, code: -1, userInfo: ["errorMessage":"空数据"])
    
    func DDPostRequest(urlStr: String, paras: [String: AnyObject], finished: DDNetFinishedCT) {
       POST(urlStr, parameters: paras, success: { (_, DATA) -> Void in
        if let result = DATA {
            finished(result: result as? [String : AnyObject], error: nil)
        }else{
            finished(result: nil, error: self.DDError)
        }
        }) { (_, error) -> Void in
            finished(result: nil, error: error)
        }
    }
    
    func DDGetRequest(urlStr: String, paras: [String:AnyObject],finished: DDNetFinishedCT) {
      GET(urlStr, parameters: paras, success: { (_, data) -> Void in
        
        // 此处的可选？ 因为finished里面定义了？，而GET方法返回的是！，所以要用一个变量接收结果，并将其转换为？，但是error就没有转换啊。
        if let result = data {
            finished(result: result as? [String : AnyObject], error: nil)
        }else{
            // TODO: 此处用private修饰为出错？
            finished(result: nil, error: self.DDError)
        }
        }) { (_, error) -> Void in
            // FIXME: 此处和上面的回调里面定义的参数没有提示？
            finished(result: nil, error: error)
        }
    }
    
}
